package cn.lgwen.candy.runtime.queue;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 2019/12/24
 * aven.wu
 * danxieai258@163.com
 * block memory queue
 */
public class MemoryBlockQueue<T> implements Queue<T> {

    private LinkedBlockingQueue<T> blockingQueue;

    private final int size;

    private final ReentrantLock takeLock = new ReentrantLock();
    private final Condition notEmpty = takeLock.newCondition();

    private AtomicBoolean isFull = new AtomicBoolean(false);


    public MemoryBlockQueue() {
        size = 10 * 1000;
        blockingQueue = new LinkedBlockingQueue<>(size);
    }

    public MemoryBlockQueue(int size) {
        this.size = size;
        blockingQueue = new LinkedBlockingQueue<>(size);
    }

    @Override
    public void add(T t) {
        synchronized (notEmpty) {
            try {
                blockingQueue.add(t);
            } catch (IllegalStateException e) {
                try {
                    // 当前线程进入等待
                    isFull.set(true);
                    notEmpty.wait();
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
                this.add(t);
            }
        }

    }

    @Override
    public T take() {
        try {
            return blockingQueue.take();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (isFull.get()) {
                notEmpty.signal();
                isFull.set(false);
            }
        }
    }

}
